package com.xmltest.demo.add;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author xuehu
 * @date 2021/2/26 16:08
 */

public class Add {
    /**
     * 1.往student.xml里面写入一个数据
     * <students>
     * <student id="03">
     * <name></name>
     * <age></age>
     * </student>
     * </students>
     * <p>
     * 1.首先定义数据
     * 2.写数据
     * IO流
     * 3.关闭流
     *
     * @param args
     */
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("java-xml/student.xml"));
        Element rootElement = document.getRootElement();
        //根标签下添加子标签并设置属性
        Element student = rootElement.addElement("student").addAttribute("id", "03");
        //像student标签添加内容
        student.addElement("name").addText("王大锤");
        student.addElement("age").addText("28");

        show("", document);
    }

    private static void show(String filePath, Document document) throws IOException {
        //指定格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置字符编码
        format.setEncoding("UTF-8");
        //向XML文件中写数据
        XMLWriter xmlWriter
                = new XMLWriter(new FileWriter(new File("java-xml/student.xml")), format);
        xmlWriter.write(document);

        xmlWriter.close();

    }
}
